import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import mpld3
from mpld3 import plugins

# 定义爱心的参数方程
def heart_3d(t):
    x = 16 * np.sin(t) ** 3
    y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)
    z = np.sin(t) * np.cos(t)
    return x, y, z

# 生成数据点
t = np.linspace(0, 2 * np.pi, 1000)
x, y, z = heart_3d(t)

# 创建3D图形
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# 绘制爱心
heart_line, = ax.plot(x, y, z, color='red', linewidth=2)

# 添加粒子效果
num_particles = 100
particles_x = np.random.normal(0, 10, num_particles)
particles_y = np.random.normal(0, 10, num_particles)
particles_z = np.random.normal(0, 10, num_particles)

particles, = ax.plot(particles_x, particles_y, particles_z, 'bo', markersize=2)

# 更新粒子位置的函数
def update_particles(frame):
    global particles_x, particles_y, particles_z
    particles_x += np.random.normal(0, 0.1, num_particles)
    particles_y += np.random.normal(0, 0.1, num_particles)
    particles_z += np.random.normal(0, 0.1, num_particles)
    particles.set_data(particles_x, particles_y)
    particles.set_3d_properties(particles_z)
    return particles,

# 创建动画
import matplotlib.animation as animation
ani = animation.FuncAnimation(fig, update_particles, frames=100, interval=50, blit=True)

# 将动画转换为HTML
html_str = mpld3.fig_to_html(fig)

# 保存为HTML文件
with open('heart_with_particles.html', 'w') as f:
    f.write(html_str)

print("HTML文件已生成：heart_with_particles.html")
